﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using LetiLib.Device;
using System.Diagnostics;

namespace LetiLib.Utils
{
    public sealed class Logger
    {
        #region | Singleton construction |
        private static readonly Lazy<Logger> lazy =
            new Lazy<Logger>(() => new Logger());

        public static Logger Instance { get { return lazy.Value; } }
        #endregion

        Dictionary<string, StringBuilder> LogTable = new Dictionary<string, StringBuilder>();
        private string mActiveItem = "";
        public void setActiveIndex(string item)
        {
            if (LogTable.ContainsKey(item))
                mActiveItem = item;
            else
                mActiveItem = "";
        }

        public void Clear()
        {
            if (LogTable != null)
                LogTable.Clear();
        }

        public void Register(BaseDevice device)
        {
            if (device != null && !LogTable.ContainsKey(device.IMEI))
                LogTable.Add(device.IMEI, new StringBuilder());
        }

        public bool Deregister(BaseDevice device)
        {
            if (device != null && LogTable.ContainsKey(device.IMEI))
                return LogTable.Remove(device.IMEI);
            
            return false;
        }

        public bool Log(BaseDevice sender, string content)
        {
            StringBuilder sbDevice;
            if (LogTable.TryGetValue(sender.IMEI,out sbDevice))
            {
                string temp = DateTime.Now.ToLongTimeString() + " " +
                    DateTime.Now.ToShortDateString() + ": " +
                    content + "\r\n";
                sbDevice.Append(temp);
                try
                {
                    File.AppendAllText(sender.LogPath, temp);
                    Debug.WriteLine(temp);
                }
                catch (System.Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
                

                if (DataLogged != null && mActiveItem.Equals(sender.IMEI))
                {
                    DataLogged(temp);
                }
            }
            return false;
        }

        public delegate void LogHandler(string content);
        public event LogHandler DataLogged;
    }
}
